package org.dromara.common.dynamicDs.config;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import org.dromara.common.core.constant.TenantConstants;
import org.dromara.common.dynamicDs.init.DynamicDsInit;
import org.dromara.common.satoken.utils.LoginHelper;


import java.io.IOException;

/**
 * @author: gxp
 * @desc: todo
 * @create: 2024-09-26 14:46
 **/
@WebFilter(urlPatterns = "/*", filterName = "dynamicDsFilter")
public class DynamicDsFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(request);
        if(LoginHelper.isLogin()){
            String dsName=DynamicDsInit.getDsName(LoginHelper.getTenantId());
            requestWrapper.addHeader(TenantConstants.TENANT_DS_KEY,dsName);
            requestWrapper.addHeader(TenantConstants.HEAD_TENANT_ID,LoginHelper.getTenantId());
        }else{
            requestWrapper.addHeader(TenantConstants.TENANT_DS_KEY, TenantConstants.DEFAULT_TENANT_DS_NAME);
            requestWrapper.addHeader(TenantConstants.HEAD_TENANT_ID,TenantConstants.DEFAULT_TENANT_ID);
        }
        filterChain.doFilter(requestWrapper, servletResponse);
    }
}
